package com.linmo.historymanage;

import com.linmo.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class HistoryManage {

    private static final Logger log = LoggerFactory.getLogger(HistoryManage.class);

    // 加载历史记录（历史记录面板）
    public List<HistoryRecordDTO> loadHistory(int userId) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "SELECT id, create_time, update_time FROM history_sessions where user_id=? ORDER BY update_time DESC";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            ResultSet rs = statement.executeQuery();

            // 提取 ResultSet 数据到 List
            List<HistoryRecordDTO> resultList = new ArrayList<>();
            while (rs.next()) {
                int sessionId = rs.getInt("id");
                Timestamp createdTime = rs.getTimestamp("create_time");
                Timestamp updatedTime = rs.getTimestamp("update_time");

                resultList.add(new HistoryRecordDTO(sessionId, createdTime, updatedTime));
            }

            log.info("加载历史记录成功:{}", resultList);
            return resultList;

        } catch (SQLException e) {
            log.error("加载历史记录出错", e);
            throw new RuntimeException(e);
        }

    }

    // 保存历史记录
//    public void saveHistory(int userId, String question, String answer) {
//        try (Connection connection = DBUtil.getConnection()) {
//            String sql = "INSERT INTO history (user_id, question, answer, create_time) VALUES (?, ?, ?,?)";
//            PreparedStatement statement = connection.prepareStatement(sql);
//            statement.setInt(1, userId);
//            statement.setString(2, question);
//            statement.setString(3, answer);
//            statement.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
//            int rows = statement.executeUpdate();
//            if (rows > 0) {
//                log.info("保存历史记录成功:{}", rows);
//            } else {
//                log.error("保存历史记录失败");
//            }
//        } catch (SQLException e) {
//            log.error("保存历史记录出错", e);
//            throw new RuntimeException(e);
//        }
//    }

    //保存历史消息
    public void saveMessage(int sessionId, String role, String message) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "INSERT INTO session_records (session_id, role, message) VALUES (?, ?, ?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, sessionId);
            statement.setString(2, role);
            statement.setString(3, message);

            int rows = statement.executeUpdate();
            if (rows > 0) {
                log.info("保存历史消息成功:{}", rows);
            } else {
                log.error("保存历史消息失败");
            }
        } catch (SQLException e) {
            log.error("保存历史消息出错", e);
            throw new RuntimeException(e);
        }
    }

    // 清空历史记录
    public void clearHistory(int userId) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "DELETE FROM history_sessions WHERE user_id = ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            int rows = statement.executeUpdate();
            if (rows > 0) {
                log.info("清空历史记录成功:{}", rows);
            } else {
                log.error("清空历史记录失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
